import 'dart:io';
import 'dart:typed_data';

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:image_picker/image_picker.dart';
import 'package:multi_image_picker/multi_image_picker.dart';
import 'package:shopping_group/entity/dim_fileinfo_entity.dart';
import 'package:shopping_group/res/colors.dart';
import 'package:shopping_group/res/dimens.dart';
import 'package:video_thumbnail/video_thumbnail.dart';
// import 'package:http_parser/src/media_type.dart';
import 'log_util.dart';
import 'object_util.dart';
import 'permission_utils.dart';
import 'widget_utils.dart';

class PhotoUtils {
  static BuildContext simpleDialogContext;

  static Widget getPhotoWidget(List<DimFileinfoEntity> listPhoto, BuildContext context, String actionType,
      {Function startPhoto,
      Function delPhoto,
      String title: '上传照片',
      bool takePhoto: false,
      bool multipartFiles: false}) {
    return Container(
      margin: const EdgeInsets.symmetric(vertical: 8),
      child: Row(
        children: <Widget>[
          GestureDetector(
            onTap: (() {
              if ('video' == actionType) {
                _videoDialogFuture(context, actionType, startPhoto: startPhoto);
              } else {
                if (Platform.isIOS) {
                  _takePhoto(actionType, startPhoto: startPhoto);
                } else {
                  PermissionUtils.isCameraPermission(context).then((data) {
                    if (null != data && data is bool && data) {
                      if (takePhoto) {
                        _takePhoto(actionType, startPhoto: startPhoto);
                      } else {
                        _photoDialogFuture(context, actionType, startPhoto: startPhoto);
                      }
                    } else {
                      BotToast.showText(text: '请打开sd卡读取权限');
                    }
                  });
                }
              }
            }),
            child: Container(
              decoration: BoxDecoration(
                color: Colours.shiping_pic,
                borderRadius: BorderRadius.circular(10),
              ),
              padding: const EdgeInsets.all(24),
              child: Column(
                children: <Widget>[
                  WidgetUtils.getImageAssetWidget('zhaopia_shipin', size: 32),
                  Padding(
                    child: WidgetUtils.getTextColorView(title, Colours.text_2222, Dimens.FONT_SIZE_12),
                    padding: const EdgeInsets.only(top: 8),
                  ),
                ],
              ),
            ),
          ),
          Expanded(
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 5),
              child: buildScrollview(listPhoto, delPhoto: delPhoto),
            ),
          ),
        ],
      ),
    );
  }

  static Widget buildScrollview(List<DimFileinfoEntity> listPhoto, {Function delPhoto, bool isHide: false}) {
    return SingleChildScrollView(
      //滑动的方向 Axis.vertical为垂直方向滑动，Axis.horizontal 为水平方向
      scrollDirection: Axis.horizontal,
      //true 滑动到底部
      reverse: false,
      padding: EdgeInsets.all(0.0),
      //滑动到底部回弹效果
      physics: BouncingScrollPhysics(),
      child: Row(
        children: listPhoto.map((DimFileinfoEntity dimFileinfoEntity) {
          return buildGridView(dimFileinfoEntity, delPhoto: delPhoto, isHide: isHide); //赋值后的Widget
        }).toList(),
      ),
    );
  }

  //获取gridviw高度
  static getheight(List<String> listPhoto) {
    double a = 0;
    if (listPhoto.length % 3 > 0) {
      a = listPhoto.length / 3 + 1;
    } else {
      a = listPhoto.length / 3;
    }
    int b = a ~/ 1;

    return b;
  }

  static Widget buildGridView(DimFileinfoEntity dimFileinfoEntity, {Function delPhoto, bool isHide: false}) {
    return Stack(
      alignment: const FractionalOffset(1, 0),
      children: <Widget>[
        GestureDetector(
          onTap: () {},
          child: ClipRRect(
              borderRadius: BorderRadius.circular(20),
              child: Container(
                width: 100.0,
                height: 100.0,
                margin: const EdgeInsets.all(5.0),
                child: ObjectUtil.isEmptyList(dimFileinfoEntity.imageData)
                    ? FadeInImage.assetNetwork(
                        image: dimFileinfoEntity.filePath,
                        placeholder: 'images/picture_loading.png' /* 指定gif */,
                        fit: BoxFit.cover,
                      )
                    : Image.memory(
                        Uint8List.fromList(dimFileinfoEntity.imageData),
                        fit: BoxFit.cover,
                      ),
              )),
        ),
        Offstage(
          offstage: isHide,
          child: Container(
            width: 32,
            height: 32,
            child: FloatingActionButton(
              heroTag: DateTime.now(),
              backgroundColor: Colours.themeColor,
              onPressed: () {
                delPhoto(dimFileinfoEntity);
              },
              child: Icon(
                Icons.clear,
                color: Colors.white,
              ),
            ),
          ),
        ),
      ],
    );
  }

  static Future _videoDialogFuture(context, actionType, {Function startPhoto}) async {
    Future result = showDialog(
        context: context,
        builder: (context) {
          simpleDialogContext = context;
          return createSimpleDialog('视频录像', '选择视频');
        });
    result.then((var select) {
      if (null == select) {
        return;
      }
      if (select is String && select == ('camera')) {
        _takeVideo(actionType, startPhoto: startPhoto);
      } else if (select is String && select == ('gallery')) {
        _selectVideo(actionType, startPhoto: startPhoto);
      }
    });
  }

  static Future _photoDialogFuture(context, actionType, {Function startPhoto}) async {
    Future result = showDialog(
        context: context,
        builder: (context) {
          simpleDialogContext = context;
          return createSimpleDialog('相机拍照', '选择照片');
        });
    result.then((var select) {
      if (null == select) {
        return;
      }
      if (select is String && select == ('camera')) {
        _takePhoto(actionType, startPhoto: startPhoto);
      } else if (select is String && select == ('gallery')) {
        _selectPhoto(actionType, startPhoto: startPhoto);
      }
    });
  }

  static Widget createSimpleDialog(String titleOne, String titleTwo) {
    return Stack(
      fit: StackFit.expand,
      children: <Widget>[
        SimpleDialog(
          title: WidgetUtils.getTextView('选择', Dimens.FONT_SIZE_18),
          children: <Widget>[
            SimpleDialogOption(
              child: WidgetUtils.getTextView(titleOne, Dimens.FONT_SIZE_16),
              onPressed: () {
                Navigator.of(simpleDialogContext).pop('camera');
              },
            ),
            SimpleDialogOption(
              child: WidgetUtils.getTextView(titleTwo, Dimens.FONT_SIZE_16),
              onPressed: () {
                Navigator.of(simpleDialogContext).pop('gallery');
              },
            ),
          ],
        ),
      ],
    );
  }

  /*拍照*/
  static Future _takePhoto(actionType, {Function startPhoto}) async {
    Future image = ImagePicker().getImage(source: ImageSource.camera);
    startPhotoSource(image, actionType, startPhoto: startPhoto, isPhoto: true);
  }

  /*录像*/
  static Future _takeVideo(actionType, {Function startPhoto}) async {
    Future video = ImagePicker().getVideo(source: ImageSource.camera);
    startVideoSource(video, actionType, startPhoto: startPhoto, isPhoto: true);
  }

  /*选择视频*/
  static Future _selectVideo(actionType, {Function startPhoto}) async {
    Future video = ImagePicker().getVideo(source: ImageSource.gallery);
    startVideoSource(video, actionType, startPhoto: startPhoto, isPhoto: true);
  }

  /*选择图片*/
  static Future _selectPhoto(actionType, {Function startPhoto}) async {
    //Future image = ImagePicker.pickImage(source: ImageSource.gallery);
    startPhotoSource(loadAssets(), actionType, startPhoto: startPhoto, isPhoto: false);
  }

  static Future startVideoSource(Future video, actionType, {Function startPhoto, bool isPhoto}) async {
    Future.wait([video]).then((results) {
      List result = List.from(results);
      if (result[0] is PickedFile) {
        PickedFile videoFile = result[0];
        Future<String> thumbnailPath = VideoThumbnail.thumbnailFile(
            video: videoFile.path, imageFormat: ImageFormat.PNG, maxHeight: 400, maxWidth: 640, quality: 80);

        thumbnailPath.then((path) async {
          Uri myUri = Uri.parse(path);
          File audioFile = File.fromUri(myUri);
          await audioFile.readAsBytes().then((value) {
            Uint8List byteData = Uint8List.fromList(value);
            List<int> imageData = byteData.buffer.asUint8List();
            // _upLoadImage(file.path, fileType, startPhoto: startPhoto);
            addDimFileInfo(imageData, '', actionType, startPhoto: startPhoto, videoPath: videoFile.path);
          });
        });
      }
    });
  }

  static Future loadAssets() async {
    List<Asset> resultList = List<Asset>();
    List<Asset> images = List<Asset>();
    resultList = await MultiImagePicker.pickImages(
        maxImages: 15,
        enableCamera: true,
        selectedAssets: images,
        cupertinoOptions: CupertinoOptions(takePhotoIcon: "chat"),
        materialOptions: MaterialOptions(
          actionBarColor: "#abcdef",
          actionBarTitle: "Example App",
          allViewTitle: "All Photos",
          selectCircleStrokeColor: "#000000",
        ));
    return resultList;
  }

  static Future startPhotoSource(Future image, actionType, {Function startPhoto, bool isPhoto}) async {
    Future.wait([image]).then((results) {
      List result = List.from(results);
      // if (result[0] is Asset) {
      //   selectPhotos(result[0], fileType, startPhoto);
      // } else
      if (isPhoto) {
        if (result[0] is PickedFile) {
          PickedFile imageFile = result[0];
          // Future reply = messageImageChannel.send(imageFile.path);
          Future<File> reply = FlutterImageCompress.compressAndGetFile(
            imageFile.path,
            imageFile.path,
            minWidth: 640,
            minHeight: 400,
            quality: 80,
          );

          LogUtil.e('imageFile:' + imageFile.path, tag: 'startPhotoSource......');
          reply.then((file) async {
            Uri myUri = Uri.parse(file.path);
            File audioFile = File.fromUri(myUri);
            await audioFile.readAsBytes().then((value) {
              Uint8List byteData = Uint8List.fromList(value);
              List<int> imageData = byteData.buffer.asUint8List();
              // _upLoadImage(file.path, fileType, startPhoto: startPhoto);
              addDimFileInfo(imageData, '', actionType, startPhoto: startPhoto);
            });
          });
        }
      } else {
        if (result[0] is List<Asset>) {
          List<Asset> imageFiles = result[0];
          for (var asset in imageFiles) {
            selectPhotos(asset, actionType, startPhoto);
          }
        }
        // else {
        //   if (result[0] is File) {
        //     File imageFile = result[0];
        //     selectPhotos(imageFile.path, fileType, startPhoto);
        //   }
        // }
      }
    }).catchError((e) {
      print(e);
    });
  }

  static selectPhotos(Asset asset, actionType, startPhoto) async {
    ByteData byteData = await asset.getByteData();
    List<int> imageData = byteData.buffer.asUint8List();
    // _upLoadImage(path, fileType, startPhoto: startPhoto);
    Future<List<int>> reply = FlutterImageCompress.compressWithList(
      imageData,
      minWidth: 640,
      minHeight: 400,
      quality: 80,
    );
    reply.then((file) {
      LogUtil.e('imageFilesssss _path:', tag: 'startPhotoSource sssss......');
      //_upLoadImage(file.path, fileType, startPhoto: startPhoto);
      addDimFileInfo(
        file,
        '',
        actionType,
        startPhoto: startPhoto,
      );
    });
  }

  static addDimFileInfo(path, url, actionType, {Function startPhoto, String videoPath}) {
    DimFileinfoEntity dimFileinfoVO = DimFileinfoEntity();
    dimFileinfoVO
      ..relaSrckey = ''
      ..relaSrctab = ''
      ..fileType = actionType
      ..fileBtype = 'photo'
      ..fileSdcardPath = ''
      ..imageData = path
      ..videoPath = videoPath
      ..filePath = url;

    startPhoto(dimFileinfoVO);
  }
}
